import net.minecraft.block.BlockState
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.VertexConsumerProvider
import net.minecraft.client.render.block.entity.BlockEntityRenderer
import net.minecraft.client.render.block.entity.BlockEntityRendererProvider
import net.minecraft.client.renderer.blockentity.SignBlockEntityRenderer
import net.minecraft.client.renderer.blockentity.SignBlockEntityRenderer.SignModel
import net.minecraft.client.renderer.blockentity.SignBlockEntityRenderer.SignType
import net.minecraft.client.renderer.texture.TextureAtlas
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.texture.TextureMap
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.client.util.math.Vector3f
import net.minecraft.util.SignTypeUtil
import net.minecraft.world.World

class YourCustomSignBlockRenderer(context: BlockEntityRendererProvider.Context) :
    BlockEntityRenderer<YourCustomSignBlockEntity?> {
    private val model: SignModel

    init {
        model = SignModel(context.getLayerModelPart(RenderLayer::getSignLayer))
    }

    fun render(
        signBlockEntity: YourCustomSignBlockEntity,
        tickDelta: Float,
        matrices: MatrixStack,
        vertexConsumers: VertexConsumerProvider?,
        light: Int,
        overlay: Int
    ) {
        matrices.push()

        // Translate the matrix to the block position
        matrices.translate(
            signBlockEntity.getPos().getX(),
            signBlockEntity.getPos().getY(),
            signBlockEntity.getPos().getZ()
        )

        // Rotate the matrix based on the block's facing direction
        matrices.mulPose(
            Vector3f.YP.rotationDegrees(
                signBlockEntity.getCachedState().get(SignBlock.FACING).getHorizontalAngle()
            )
        )
        val world: World = signBlockEntity.getWorld()
        val blockState: BlockState = signBlockEntity.getCachedState()
        val signType: SignType = SignTypeUtil.getType(world, blockState.getBlock())
        val atlas: TextureAtlas = context.getTextureManager().getTexture(TextureMap.LOCATION_BLOCKS)
        SignBlockEntityRenderer.SignTypeUtil.bindTexture(atlas, signType)
        matrices.scale(1.0f, -1.0f, -1.0f)
        val textureAtlasSprite: TextureAtlasSprite = getTexture(signType)
        val f: Float = textureAtlasSprite.getU0()
        val g: Float = textureAtlasSprite.getU1()
        val h: Float = textureAtlasSprite.getV0()
        val i: Float = textureAtlasSprite.getV1()
        SignBlockEntityRenderer.renderText(
            signBlockEntity,
            tickDelta,
            matrices,
            vertexConsumers,
            light,
            overlay,
            textureAtlasSprite
        )
        matrices.pop()
    }

    @Nullable
    private fun getTexture(type: SignType): TextureAtlasSprite {
        return model.getSignTextures().get(type)
    }
}